<?php
/**
 * Created by PhpStorm.
 * User: 13469
 * Date: 2018/10/9
 * Time: 15:35
 */
include "config.php";
if($_SERVER["REQUEST_METHOD"]=="POST"){
    //看数据库接收哪些数据
    if(isset($_POST["u_id"])&&isset($_POST["c_id"])&&isset($_POST["c_name"])&&isset($_POST["c_price"])&&isset($_POST["c_num"])&&isset($_POST["c_path"])){
       //查询数据数据 有没有该用户id和产品id
        $sql="SELECT *FROM carts WHERE u_id=? AND c_pro_id=?";
        $stmt=$conn->prepare($sql);
        $stmt->bind_param("ii",$_POST["u_id"],$_POST["c_id"]);
        $stmt->execute();
        $res=$stmt->get_result();

        if($res->num_rows>=1){
            //有 就修改数据
            $updateSql="UPDATE carts SET c_num=c_num+1,c_total=c_num*c_price WHERE u_id=? AND c_pro_id=?";
            $stmt=$conn->prepare($updateSql);
            $stmt->bind_param("ii",$_POST["u_id"],$_POST["c_id"]);
           $stmt->execute();
            if($stmt->affected_rows>=1){
                print_r(json_encode(array("status"=>2,"msg"=>"加入成功u")));
            }else{
                print_r(json_encode(array("status"=>-2,"msg"=>"加入失败u")));
            }
        } else{
            //没有 就添加数据
            $insertSql="INSERT INTO carts (`u_id`,`c_name`,`c_price`,`c_num`,`c_total`,`c_path`,`c_pro_id`)VALUES(?,?,?,?,?,?,?)
";           $stmt=$conn->prepare($insertSql);
            $total=intval($_POST["c_num"])*floatval($_POST["c_price"]);
            $stmt->bind_param("ississi",$_POST["u_id"],$_POST["c_name"],$_POST["c_price"],$_POST["c_num"],$total,$_POST["c_path"],$_POST["c_id"]);
            $stmt->execute();
            if($stmt->affected_rows>=1){
                print_r(json_encode(array("status"=>1,"msg"=>"加入成功i")));
            }else{
                print_r(json_encode(array("status"=>-1,"msg"=>"加入失败i")));
            }
        }
    }else{
        print_r(json_encode(array("status"=>-3,"msg"=>"参数不合法")));
    }

}else{
    print_r(json_encode(array("status"=>0,"msg"=>"不支持get请求")));
}